<template>
  <div>
    <el-dialog
      v-model="show"
      :title="title"
      width="500"
      draggable
      destroy-on-close
      @close="reset"
    >
      <div>
        <el-form
          :model="formData"
          label-width="auto"
          style="max-width: 600px"
          :rules="rules"
          ref="ruleForm"
          :mode="ruleModel"
        >
          <el-form-item label="分类名称" prop="name">
            <el-input v-model.trim="formData.name" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="reset">取消</el-button>
          <el-button type="primary" @click="onSubmit"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { defineExpose, ref, defineEmits } from "vue";

const emits = defineEmits(["common"]);
const show = ref(false);
const title = ref("添加分类");

const ruleForm = ref();
const rules = ref({
  name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
});

const formData = ref({
  id: null,
  name: "",
  flag: 1,
});

const open = (item, type) => {
  show.value = true;
  title.value = type;
  if ("修改分类" === type) {
    formData.value.id = item.id;
    formData.value.name = item.name;
    formData.value.flag = 0;
  }
};

const ruleModel = ref({
  name: "",
});

const onSubmit = () => {
  ruleForm.value.validate((valid) => {
    if (valid) {
      emits("common", formData.value);
      reset();
    }
  });
};

const reset = () => {
  formData.value = {
    id: null,
    name: "",
    flag: 1,
  };
  show.value = false;
};

defineExpose({
  open,
});
</script>

<style></style>
